import { Toast } from "@/app/components/Toast";
import { BASE_URL } from "@/utils/env";
import axios from "axios";
import i18next from 'i18next';

import type { AxiosError, AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from 'axios'

const instance: AxiosInstance = axios.create({
  baseURL: BASE_URL,
//   timeout: 10000,
  headers: {
    "Content-Type": "application/json"
  }
})

// 请求拦截
// instance.interceptors.request.use(
//   async (config: InternalAxiosRequestConfig): Promise<InternalAxiosRequestConfig> => {
//     return config;
//   },
//   (error: AxiosError): Promise<AxiosError> => {
//     return Promise.reject(error);
//   }
// );

// 响应拦截
instance.interceptors.response.use(
  (response: AxiosResponse): Promise<AxiosResponse> => {
    const { data } = response
    if (data?.code === 0) {
      return Promise.resolve(response.data)
    } else {
      Toast.center(data?.msg)
      return Promise.reject(data)
    }
  },
  (error: AxiosError): Promise<AxiosError> => {
    let msg = error.message
    if(error.code === 'ECONNABORTED'){
      msg = i18next.t('Network exception.. Please try again.')
    }
    Toast.center(msg)
    return Promise.reject(error);
  }
);

type Method = 'get' | 'post' | 'put' | 'delete' | 'patch'
export default async function request(url: string, params: Record<string, any> | FormData, method: Method): Promise<AxiosResponse> {

  return instance.request({
    url,
    method,
    data: ["put", "post", "delete", "patch"].includes(method.toLocaleLowerCase()) ? params : undefined,
    params: !["put", "post", "delete", "patch"].includes(method.toLocaleLowerCase()) ? params : undefined,
  })
}